package com.huangliusong;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
/**
 * @author huangliusong
 * @since 2019/1/26
 * {@link Watcher}
 */
public class ZKConnectSessionWatcher implements Watcher{
    public static Logger log = LoggerFactory.getLogger(ZKConnectSessionWatcher.class);
    public static final String zkServerPath = "192.168.1.101:2181";

    /** 超时时间 单位ms
     *  这个timeout是超时时间，就是服务和客户端之间会有心跳，超过这个时间就默认客户端已死
     */
    public static final Integer timeout = 10000;



    public static void main(String args[]){
        try {
            ZooKeeper zk = new ZooKeeper(zkServerPath,timeout,new ZKConnectSessionWatcher());
            log.warn("客户端开始连接zookeeper服务器");
            log.warn("连接状态：{}" + zk.getState());
            Thread.sleep(2000);
            int sessionTimeout = zk.getSessionTimeout();
            log.warn("sessionTimeout:"+sessionTimeout);
            //获取zk会话ID
            long sessionId = zk.getSessionId();
            System.err.println("sessionId:"+sessionId);
            //64进制转码
            String ssid = "0x" + Long.toHexString(sessionId);
            log.warn("ssid:"+ssid);
            //获取zk会话密码
            byte[] sessionPassword = zk.getSessionPasswd();
            log.warn("连接状态：{}" + zk.getState());

            Thread.sleep(200);
            log.warn("开始会话重连");
            ZooKeeper zkSession = new ZooKeeper(zkServerPath,timeout,new ZKConnectSessionWatcher(),sessionId,sessionPassword);
            log.warn("连接状态：{}" + zkSession.getState());
            Thread.sleep(1000);
            log.warn("连接状态：{}" + zkSession.getState());
        } catch (IOException e) {
            log.error(e.toString());
        } catch (InterruptedException e) {
            log.error(e.toString());
        }
    }


    public void process(WatchedEvent watchedEvent) {
        log.warn("接受到watch通知" + watchedEvent);
    }
}